package com.rslai.base.tool.servertest.transport.dubbo;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.rslai.base.tool.servertest.transport.model.ServiceDesc;
import com.rslai.base.tool.servertest.util.PropertyUtils;
import com.rslai.base.tool.servertest.util.ReflectionUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;

public class DubboServiceFactory {
    private static final Map<String, Object> serviceCache = new ConcurrentHashMap();

    public static Object getRpcService(ServiceDesc serviceDesc) {
        String rpcUrl = getRpcServiceUrl(serviceDesc.getUrl());
        Class<?> interfaceClass = ReflectionUtils.loadClass(serviceDesc.getClazz());
        String cacheKey = serviceDesc.getCacheKey();
        Object service = serviceCache.get(cacheKey);
        if (service == null) {
            synchronized (serviceCache) {
                ApplicationConfig application = new ApplicationConfig();
                application.setName(PropertyUtils.getProperty("dubbo.appName", "test"));
                ReferenceConfig<?> reference = new ReferenceConfig();
                reference.setApplication(application);
                reference.setInterface(interfaceClass);
                if ((StringUtils.isNotBlank(serviceDesc.getVersion())) && (!serviceDesc.getVersion().equals("*"))) {
                    reference.setVersion(serviceDesc.getVersion());
                }
                reference.setUrl(rpcUrl);
                if (StringUtils.isNotBlank(serviceDesc.getGroup())) {
                    reference.setGroup(serviceDesc.getGroup());
                }
                reference.setTimeout(Integer.valueOf(PropertyUtils.getProperty("dubbo.timeout", "3000")));
                service = reference.get();
                serviceCache.put(cacheKey, service);
            }
        }
        return service;
    }

    private static String getRpcServiceUrl(String url) {
        StringBuilder sb = new StringBuilder(PropertyUtils.getProperty("dubbo.protocol", "dubbo"));
        sb.append("://");
        sb.append(url);
        if (sb.indexOf(":") == -1) {
            sb.append(":").append("20880");
        }
        return sb.toString();
    }
}

